/**
 * 电脑键盘按键背景灯可视化器
 */
class KeyboardLightsVisualizer extends VisualizerInterface {
    constructor(canvas, ctx) {
        super(canvas, ctx);
        this.keys = [];
        this.keyLayout = [];
        this.keyAnimations = [];
        this.ripples = [];
    }

    getInfo() {
        return {
            name: 'Keyboard Lights',
            description: '电脑键盘按键RGB背景灯效果',
            author: 'AudioNN',
            version: '1.0.0',
            category: 'gaming'
        };
    }

    getDefaultSettings() {
        return {
            ...super.getDefaultSettings(),
            keyboardType: 'tkl', // full, tkl, 60percent
            lightingMode: 'wave', // wave, reactive, spectrum, breathing
            waveSpeed: 0.05,
            rippleEffect: true,
            keySpacing: 2,
            cornerRadius: 4,
            glowIntensity: 1.0,
            colorMode: 'rainbow', // rainbow, spectrum, single
            singleColor: '#00FF00'
        };
    }

    getConfigurableParams() {
        return [
            ...super.getConfigurableParams(),
            {
                key: 'keyboardType',
                label: '键盘类型',
                type: 'select',
                options: [
                    { value: 'full', label: '全尺寸键盘' },
                    { value: 'tkl', label: 'TKL键盘' },
                    { value: '60percent', label: '60%键盘' }
                ],
                default: 'tkl'
            },
            {
                key: 'lightingMode',
                label: '灯光模式',
                type: 'select',
                options: [
                    { value: 'wave', label: '波浪效果' },
                    { value: 'reactive', label: '反应模式' },
                    { value: 'spectrum', label: '频谱模式' },
                    { value: 'breathing', label: '呼吸模式' }
                ],
                default: 'wave'
            },
            {
                key: 'waveSpeed',
                label: '波浪速度',
                type: 'range',
                min: 0.01,
                max: 0.1,
                step: 0.01,
                default: 0.05
            },
            {
                key: 'rippleEffect',
                label: '水波纹效果',
                type: 'boolean',
                default: true
            },
            {
                key: 'glowIntensity',
                label: '发光强度',
                type: 'range',
                min: 0.5,
                max: 2.0,
                step: 0.1,
                default: 1.0
            }
        ];
    }

    init(config = {}) {
        super.init(config);
        this.initializeKeyboard();
        this.waveOffset = 0;
        this.breathingPhase = 0;
        return this;
    }

    initializeKeyboard() {
        this.keys = [];
        this.keyAnimations = [];
        this.keyLayout = this.getKeyboardLayout();
        
        const width = this.canvas.width / window.devicePixelRatio;
        const height = this.canvas.height / window.devicePixelRatio;
        
        // 计算键盘尺寸和位置
        const keyboardWidth = this.keyLayout[0].length * 40 + (this.keyLayout[0].length - 1) * this.settings.keySpacing;
        const keyboardHeight = this.keyLayout.length * 40 + (this.keyLayout.length - 1) * this.settings.keySpacing;
        
        const offsetX = (width - keyboardWidth) / 2;
        const offsetY = (height - keyboardHeight) / 2;
        
        // 创建按键
        this.keyLayout.forEach((row, rowIndex) => {
            row.forEach((keyData, colIndex) => {
                if (keyData) {
                    const key = {
                        x: offsetX + colIndex * (40 + this.settings.keySpacing),
                        y: offsetY + rowIndex * (40 + this.settings.keySpacing),
                        width: keyData.width || 40,
                        height: 40,
                        label: keyData.label,
                        row: rowIndex,
                        col: colIndex,
                        type: keyData.type || 'normal'
                    };
                    
                    this.keys.push(key);
                    this.keyAnimations.push({
                        intensity: 0,
                        color: { r: 0, g: 0, b: 0 },
                        glow: 0,
                        lastTrigger: 0,
                        rippleTime: 0
                    });
                }
            });
        });
    }

    getKeyboardLayout() {
        const layouts = {
            'full': this.getFullKeyboardLayout(),
            'tkl': this.getTKLKeyboardLayout(),
            '60percent': this.get60PercentLayout()
        };
        return layouts[this.settings.keyboardType] || layouts.tkl;
    }

    getTKLKeyboardLayout() {
        return [
            // 功能键行
            [
                { label: 'ESC' }, null, { label: 'F1' }, { label: 'F2' }, { label: 'F3' }, { label: 'F4' },
                null, { label: 'F5' }, { label: 'F6' }, { label: 'F7' }, { label: 'F8' },
                null, { label: 'F9' }, { label: 'F10' }, { label: 'F11' }, { label: 'F12' },
                null, { label: 'PRT' }, { label: 'SCR' }, { label: 'PAU' }
            ],
            [null], // 空行
            // 数字行
            [
                { label: '`' }, { label: '1' }, { label: '2' }, { label: '3' }, { label: '4' }, { label: '5' },
                { label: '6' }, { label: '7' }, { label: '8' }, { label: '9' }, { label: '0' }, { label: '-' },
                { label: '=' }, { label: 'BACKSPACE', width: 80 },
                null, { label: 'INS' }, { label: 'HOM' }, { label: 'PGU' }
            ],
            // 字母行1
            [
                { label: 'TAB', width: 60 }, { label: 'Q' }, { label: 'W' }, { label: 'E' }, { label: 'R' }, { label: 'T' },
                { label: 'Y' }, { label: 'U' }, { label: 'I' }, { label: 'O' }, { label: 'P' }, { label: '[' },
                { label: ']' }, { label: '\\', width: 60 },
                null, { label: 'DEL' }, { label: 'END' }, { label: 'PGD' }
            ],
            // 字母行2
            [
                { label: 'CAPS', width: 80 }, { label: 'A' }, { label: 'S' }, { label: 'D' }, { label: 'F' }, { label: 'G' },
                { label: 'H' }, { label: 'J' }, { label: 'K' }, { label: 'L' }, { label: ';' }, { label: '\'' },
                { label: 'ENTER', width: 100 }
            ],
            // 字母行3
            [
                { label: 'SHIFT', width: 120 }, { label: 'Z' }, { label: 'X' }, { label: 'C' }, { label: 'V' }, { label: 'B' },
                { label: 'N' }, { label: 'M' }, { label: ',' }, { label: '.' }, { label: '/' },
                { label: 'SHIFT', width: 120 },
                null, null, { label: '↑' }
            ],
            // 控制行
            [
                { label: 'CTRL', width: 60 }, { label: 'WIN', width: 60 }, { label: 'ALT', width: 60 },
                { label: 'SPACE', width: 240 },
                { label: 'ALT', width: 60 }, { label: 'FN', width: 60 }, { label: 'MENU', width: 60 }, { label: 'CTRL', width: 60 },
                null, { label: '←' }, { label: '↓' }, { label: '→' }
            ]
        ];
    }

    get60PercentLayout() {
        return [
            // 数字行
            [
                { label: '`' }, { label: '1' }, { label: '2' }, { label: '3' }, { label: '4' }, { label: '5' },
                { label: '6' }, { label: '7' }, { label: '8' }, { label: '9' }, { label: '0' }, { label: '-' },
                { label: '=' }, { label: 'BACKSPACE', width: 80 }
            ],
            // 字母行1
            [
                { label: 'TAB', width: 60 }, { label: 'Q' }, { label: 'W' }, { label: 'E' }, { label: 'R' }, { label: 'T' },
                { label: 'Y' }, { label: 'U' }, { label: 'I' }, { label: 'O' }, { label: 'P' }, { label: '[' },
                { label: ']' }, { label: '\\', width: 60 }
            ],
            // 字母行2
            [
                { label: 'CAPS', width: 80 }, { label: 'A' }, { label: 'S' }, { label: 'D' }, { label: 'F' }, { label: 'G' },
                { label: 'H' }, { label: 'J' }, { label: 'K' }, { label: 'L' }, { label: ';' }, { label: '\'' },
                { label: 'ENTER', width: 100 }
            ],
            // 字母行3
            [
                { label: 'SHIFT', width: 120 }, { label: 'Z' }, { label: 'X' }, { label: 'C' }, { label: 'V' }, { label: 'B' },
                { label: 'N' }, { label: 'M' }, { label: ',' }, { label: '.' }, { label: '/' },
                { label: 'SHIFT', width: 120 }
            ],
            // 控制行
            [
                { label: 'CTRL', width: 60 }, { label: 'WIN', width: 60 }, { label: 'ALT', width: 60 },
                { label: 'SPACE', width: 240 },
                { label: 'ALT', width: 60 }, { label: 'FN', width: 60 }, { label: 'MENU', width: 60 }, { label: 'CTRL', width: 60 }
            ]
        ];
    }

    getFullKeyboardLayout() {
        // 简化版全键盘布局，包含小键盘
        const tklLayout = this.getTKLKeyboardLayout();
        // 这里可以添加小键盘部分
        return tklLayout;
    }

    render(frequencyData, cachedData = null, currentTime = 0) {
        this.clearCanvas();
        
        const dataToUse = cachedData || frequencyData;
        if (!dataToUse) return;

        // 更新动画状态
        this.updateAnimations(dataToUse, currentTime);

        // 绘制键盘底座
        this.drawKeyboardBase();

        // 绘制按键
        this.drawKeys();

        // 绘制水波纹效果
        if (this.settings.rippleEffect) {
            this.drawRipples();
        }

        // 绘制光效
        this.drawLightEffects();
    }

    updateAnimations(frequencyData, currentTime) {
        this.waveOffset += this.settings.waveSpeed;
        this.breathingPhase += 0.02;

        const totalKeys = this.keys.length;
        const dataPerKey = frequencyData.length / totalKeys;

        this.keys.forEach((key, index) => {
            const animation = this.keyAnimations[index];
            const dataIndex = Math.floor(index * dataPerKey);
            const intensity = frequencyData[dataIndex] / 255;

            // 根据不同模式更新颜色和强度
            switch (this.settings.lightingMode) {
                case 'wave':
                    this.updateWaveMode(key, animation, index, intensity);
                    break;
                case 'reactive':
                    this.updateReactiveMode(key, animation, intensity);
                    break;
                case 'spectrum':
                    this.updateSpectrumMode(key, animation, index, intensity);
                    break;
                case 'breathing':
                    this.updateBreathingMode(key, animation, intensity);
                    break;
            }

            // 强度衰减
            animation.intensity *= 0.95;
            animation.glow *= 0.9;
        });

        // 更新水波纹
        this.ripples = this.ripples.filter(ripple => {
            ripple.radius += ripple.speed;
            ripple.alpha *= 0.95;
            return ripple.alpha > 0.01;
        });
    }

    updateWaveMode(key, animation, index, intensity) {
        const waveX = Math.sin(this.waveOffset + key.col * 0.5) * 0.5 + 0.5;
        const waveY = Math.cos(this.waveOffset + key.row * 0.3) * 0.5 + 0.5;
        const wave = (waveX + waveY) / 2;

        const hue = (wave * 360 + this.waveOffset * 50) % 360;
        const color = this.hslToRgb(hue, 80, 50 + intensity * 30);
        
        animation.color = { r: color[0], g: color[1], b: color[2] };
        animation.intensity = wave * 0.7 + intensity * 0.3;
    }

    updateReactiveMode(key, animation, intensity) {
        if (intensity > 0.3) {
            animation.intensity = intensity;
            animation.lastTrigger = Date.now();
            
            // 添加水波纹
            if (this.settings.rippleEffect) {
                this.ripples.push({
                    x: key.x + key.width / 2,
                    y: key.y + key.height / 2,
                    radius: 0,
                    speed: 2,
                    alpha: intensity,
                    color: this.getIntensityColor(intensity)
                });
            }
        }

        const timeSinceHit = Date.now() - animation.lastTrigger;
        const decay = Math.max(0, 1 - timeSinceHit / 1000);
        
        const color = this.getIntensityColor(intensity * decay);
        animation.color = color;
        animation.glow = intensity * decay;
    }

    updateSpectrumMode(key, animation, index, intensity) {
        const hue = (index / this.keys.length) * 360;
        const color = this.hslToRgb(hue, 90, 30 + intensity * 50);
        
        animation.color = { r: color[0], g: color[1], b: color[2] };
        animation.intensity = intensity;
        animation.glow = intensity;
    }

    updateBreathingMode(key, animation, intensity) {
        const breathing = (Math.sin(this.breathingPhase) * 0.5 + 0.5);
        const combinedIntensity = breathing * 0.7 + intensity * 0.3;
        
        const color = this.getIntensityColor(combinedIntensity);
        animation.color = color;
        animation.intensity = combinedIntensity;
    }

    drawKeyboardBase() {
        const width = this.canvas.width / window.devicePixelRatio;
        const height = this.canvas.height / window.devicePixelRatio;
        
        // 绘制键盘外壳
        const padding = 20;
        const minX = Math.min(...this.keys.map(k => k.x)) - padding;
        const minY = Math.min(...this.keys.map(k => k.y)) - padding;
        const maxX = Math.max(...this.keys.map(k => k.x + k.width)) + padding;
        const maxY = Math.max(...this.keys.map(k => k.y + k.height)) + padding;
        
        const gradient = this.ctx.createLinearGradient(minX, minY, maxX, maxY);
        gradient.addColorStop(0, 'rgba(30, 30, 30, 0.9)');
        gradient.addColorStop(1, 'rgba(10, 10, 10, 0.9)');
        
            this.ctx.fillStyle = gradient;
            this.drawRoundedRect(minX, minY, maxX - minX, maxY - minY, 15);
            this.ctx.fill();
        
        // 绘制边框
        this.ctx.strokeStyle = 'rgba(100, 100, 100, 0.5)';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
    }

    drawKeys() {
        this.keys.forEach((key, index) => {
            const animation = this.keyAnimations[index];
            
            // 绘制按键阴影
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.4)';
            this.drawRoundedRect(key.x + 2, key.y + 2, key.width, key.height, this.settings.cornerRadius);
            this.ctx.fill();
            
            // 绘制按键背景
            const bgColor = `rgba(${animation.color.r}, ${animation.color.g}, ${animation.color.b}, ${animation.intensity})`;
            this.ctx.fillStyle = bgColor;
            this.drawRoundedRect(key.x, key.y, key.width, key.height, this.settings.cornerRadius);
            this.ctx.fill();
            
            // 绘制按键边框
            this.ctx.strokeStyle = 'rgba(200, 200, 200, 0.3)';
            this.ctx.lineWidth = 1;
            this.ctx.stroke();
            
            // 绘制发光效果
            if (animation.glow > 0.1) {
                this.ctx.shadowColor = `rgb(${animation.color.r}, ${animation.color.g}, ${animation.color.b})`;
                this.ctx.shadowBlur = animation.glow * this.settings.glowIntensity * 15;
                this.ctx.strokeStyle = `rgba(${animation.color.r}, ${animation.color.g}, ${animation.color.b}, ${animation.glow})`;
                this.ctx.lineWidth = 3;
                this.ctx.stroke();
                this.ctx.shadowBlur = 0;
            }
            
            // 绘制按键标签
            this.drawKeyLabel(key, animation);
        });
    }

    drawKeyLabel(key, animation) {
        if (!key.label) return;
        
        this.ctx.fillStyle = `rgba(255, 255, 255, ${0.8 - animation.intensity * 0.3})`;
        this.ctx.font = key.width > 60 ? '10px Arial' : '8px Arial';
        this.ctx.textAlign = 'center';
        this.ctx.textBaseline = 'middle';
        
        this.ctx.fillText(
            key.label,
            key.x + key.width / 2,
            key.y + key.height / 2
        );
    }

    drawRipples() {
        this.ripples.forEach(ripple => {
            this.ctx.strokeStyle = `rgba(${ripple.color.r}, ${ripple.color.g}, ${ripple.color.b}, ${ripple.alpha})`;
            this.ctx.lineWidth = 2;
            this.ctx.beginPath();
            this.ctx.arc(ripple.x, ripple.y, ripple.radius, 0, Math.PI * 2);
            this.ctx.stroke();
        });
    }

    drawLightEffects() {
        // 绘制键盘周围的光效
        if (this.settings.lightingMode === 'wave') {
            const width = this.canvas.width / window.devicePixelRatio;
            const height = this.canvas.height / window.devicePixelRatio;
            
            // 计算平均颜色
            let avgR = 0, avgG = 0, avgB = 0;
            this.keyAnimations.forEach(anim => {
                avgR += anim.color.r * anim.intensity;
                avgG += anim.color.g * anim.intensity;
                avgB += anim.color.b * anim.intensity;
            });
            
            const count = this.keyAnimations.length;
            avgR = Math.floor(avgR / count);
            avgG = Math.floor(avgG / count);
            avgB = Math.floor(avgB / count);
            
            // 绘制周围光效
            const gradient = this.ctx.createRadialGradient(
                width / 2, height / 2, 0,
                width / 2, height / 2, Math.min(width, height) / 2
            );
            
            gradient.addColorStop(0, `rgba(${avgR}, ${avgG}, ${avgB}, 0.1)`);
            gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
            
            this.ctx.fillStyle = gradient;
            this.ctx.fillRect(0, 0, width, height);
        }
    }

    getIntensityColor(intensity) {
        // 从蓝色到红色的渐变
        const red = Math.floor(intensity * 255);
        const green = Math.floor((1 - intensity) * intensity * 255);
        const blue = Math.floor((1 - intensity) * 255);
        return { r: red, g: green, b: blue };
    }

    drawRoundedRect(x, y, width, height, radius) {
        this.ctx.beginPath();
        this.ctx.moveTo(x + radius, y);
        this.ctx.lineTo(x + width - radius, y);
        this.ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
        this.ctx.lineTo(x + width, y + height - radius);
        this.ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
        this.ctx.lineTo(x + radius, y + height);
        this.ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
        this.ctx.lineTo(x, y + radius);
        this.ctx.quadraticCurveTo(x, y, x + radius, y);
        this.ctx.closePath();
    }

    resize(width, height) {
        this.initializeKeyboard();
    }
}

// 注册可视化器到全局注册表
if (typeof window !== 'undefined') {
    if (!window.visualizerRegistrations) {
        window.visualizerRegistrations = [];
    }
    window.visualizerRegistrations.push({
        id: 'keyboard-lights',
        class: KeyboardLightsVisualizer
    });
}

window.KeyboardLightsVisualizer = KeyboardLightsVisualizer;
